package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

/**
 * * @title: RecommendUserApiImpl
 *
 * @Author Philcan
 * @Date: 2021/8/9 19:06
 * @Version 1.0
 */
@Service(validation = "1.0.0")
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private UserLikeApi userLikeApi;

    @Override
    public RecommendUser queryWithMaxScore(Long userId) {
        Query query = Query.query(Criteria.where("toUserId").is(userId)).with(Sort.by(Sort.Order.desc("score"))).limit(1);
        return this.mongoTemplate.findOne(query, RecommendUser.class);
    }

    @Override
    public PageInfo<RecommendUser> queryPageInfo(Long userId, Integer page, Integer pageSize) {
        PageRequest score = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("score")));
        Query query = Query.query(Criteria.where("toUserId").is(userId)).with(score);
        List<RecommendUser> recommendUserList = this.mongoTemplate.find(query, RecommendUser.class);
        return new PageInfo<>(0, page, pageSize, recommendUserList);
    }

    @Override
    public Double queryScore(Long userId, Long toUserId) {
        Query query = Query.query(Criteria.where("toUserId").is(toUserId).and("userId").is(userId));
        RecommendUser recommendUser = this.mongoTemplate.findOne(query, RecommendUser.class);
        if (null != recommendUser) {
            return recommendUser.getScore();
        }
        return null;
    }

    @Override
    public List<RecommendUser> queryCardList(Long userId, Integer count) {
        PageRequest pageRequest = PageRequest.of(0, count, Sort.by(Sort.Order.desc("score")));
        List<Long> userIds = new ArrayList<>();
        userIds.addAll(this.userLikeApi.queryLikeList(userId));
        userIds.addAll(this.userLikeApi.queryNotLikeList(userId));

        Criteria criteria = Criteria.where("toUserId").is(userId);
        if (CollUtil.isNotEmpty(userIds)) {
            criteria.andOperator(Criteria.where("userId").nin(userIds));
        }
        Query query = Query.query(criteria).with(pageRequest);
        List<RecommendUser> recommendUserList = this.mongoTemplate.find(query, RecommendUser.class);
        return recommendUserList;
    }
}
